import type { AppRouteRecordRaw } from './types';
import { DEFAULT_LAYOUT } from './base';
import dashboard from './modules/dashboard';
import shop from './modules/shop';

const modules = import.meta.glob('./modules/*.ts', { eager: true });
const externalModules = import.meta.glob('./externalModules/*.ts', {
  eager: true,
});

function formatModules(_modules: any, result: AppRouteRecordRaw[]) {
  Object.keys(_modules).forEach((key) => {
    const defaultModule = _modules[key].default;
    if (!defaultModule) return;
    const moduleList = Array.isArray(defaultModule)
      ? [...defaultModule]
      : [defaultModule];
    result.push(...moduleList);
  });
  return result;
}

export const DEFAULT_ROUTE_NAME = 'Workplace';

export const appRoutes = [dashboard, shop, ...formatModules(modules, [])];

export const routes: AppRouteRecordRaw[] = [
  {
    path: '/',
    name: 'root',
    component: DEFAULT_LAYOUT,
    redirect: '/dashboard/workplace',
    meta: {
      requiresAuth: true,
    },
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      requiresAuth: false,
    },
  },
  ...appRoutes,
  {
    path: '/:pathMatch(.*)*',
    name: 'notFound',
    component: () => import('@/views/not-found/index.vue'),
  },
];

export const appExternalRoutes: AppRouteRecordRaw[] = formatModules(
  externalModules,
  []
);

export default routes;
